<template>
	<view>
		<!-- 收银台 -->
		<view class="edgeInsetTop"></view>
		<view class="wanl-pay">
			<!-- <view class="enlargement">
				<view class="">点击上方“允许”按钮立即支付</view>
				<image src="../static/imgs/index/shangsheng@3x.png" mode="widthFix" class="fiximage"></image>
			</view> -->
			<view class="price-box">
				<text class="text-df">{{order_no}}</text>
				<text class="wanl-pip text-price margin-top-sm">{{price}}</text>
			</view>
			<view class="list-box">
				<view class="item" v-for="(item, index) in payList" :key="index">
					<text :class="'wlIcon-'+ item.type +'-pay'"></text>
					<view class="action">
						<text class="title wanl-pip">{{item.name}}</text>
						<view>{{item.describe}}</view>
					</view>
					<view class="radio text-xxl" v-if="item.state" @tap="onSelect(index)">
						<text v-if="item.select" class="wlIcon-xuanze-danxuan wanl-orange"></text>
						<text v-else class="wlIcon-xuanze wanl-gray-light"></text>
					</view>
					<view class="radio text-xxl" v-else>
						<text class="wlIcon-xuanze-danxuan wanl-gray-light"></text>
					</view>
				</view>
			</view>
			<view v-if="disabled">
				<button class="mix-btn wanl-bg-redorange"> <text
						class="wlIcon-jiazai wlIconfont-spin margin-right-xs"></text>正在支付中... </button>
			</view>
			<view v-else>
				<button v-if="payNum == 1" class="mix-btn wanl-bg-redorange" @tap="confirm()"> 确认支付 </button>
				<button v-else class="mix-btn wanl-bg-redorange" @tap="confirm()"> 合并支付 </button>
			</view>
			<!-- <view class="footer text-center">
				<view class="text-sm" v-if="order_pay_no">{{order_type === 'groups' ? '拼团':''}}交易号：{{order_pay_no}}</view>
				<view> © 万联支付</view>
			</view> -->
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				// token: '',
				disabled: false,
				price: '0.00',
				isbalance: false,
				order_type: 'goods',
				order_no: '',
				order_pay_no: '',
				payNum: 1, // 支付方式 独立支付-合并支付
				payList: [],
				
				payDataList: [],// 
			}
		},
		props: {
			token: {
				type: String,
				default: '',
			},
			pay_type: {
				type: String,
				default: 0,
			},
			payData: {
				type: Array,
				default: [],
			}
		},
		computed: {
			...mapState(['user'])
		},
		watch: {
			price(val, newval) {
				if (val <= parseFloat(this.$store.state.user.money)) {
					this.isbalance = true;
					this.getPayment();
				}
			}
		},
		mounted() {
			this.getData();
			// this.getopenId();
		},
		methods: {
			// async getopenId(){
			// 	await uni.request({
			// 		url: '/fuhave/openId',
			// 		method: 'POST',
			// 		success: res => {
			// 			console.log(res);
			// 		}
			// 	});
			// },
			async getData() {
				await uni.request({
					url: '/wanlshop/pay/getBalance',
					method: 'POST',
					success: res => {
						this.$store.commit('user/setUserInfo', {
							money: res.data
						});
						// 获取支付列表
						this.getPayment();
					}
				});
				if (this.payData) {
					var sum = 0
					var data = this.payData
					var order_ids = [];
					if (data.length <= 1) {

						this.price = data[0].price;
						this.order_type = data[0].type;
						this.order_no = `${data[0].type == 'groups' ? '拼团':''}订单号：${data[0].order_no}`;
						this.order_pay_no = data[0].pay_no;
						this.order_id = data[0].order_id;
					} else {
						data.forEach(item => {
							sum = this.$wanlshop.bcadd(sum, item.price);
							order_ids.push(item.order_id);
						});
						this.price = sum;
						this.order_id = order_ids;
						this.payNum = data.length;
						this.order_no = '合并支付 ' + data.length + '个订单';
					}

					uni.setStorageSync('purchase_amount', this.price)
					this.token = option.token;
				} else if (option.order_id) {
					uni.showLoading({
						title: '结算中...'
					});
					await uni.request({
						url: '/wanlshop/pay/getPay',
						method: 'POST',
						data: {
							order_id: option.order_id,
							order_type: option.order_type
						},
						success: res => {
							uni.hideLoading();
							this.token = res.data.token;
							this.price = res.data.price;
							this.order_type = res.data.order_type;
							this.order_no =
								`${res.data.order_type == 'groups' ? '拼团':''}订单号：${res.data.order_no}`;
							this.order_pay_no = res.data.pay_no;
							this.order_id = res.data.order_id;
							uni.setStorageSync('purchase_amount', this.price)
						}
					});
				} else {
					console.log('非法访问');
				}
			},
			getPayment() {
				let method = 'wap';
				// #ifdef APP-PLUS
				method = 'app';
				// #endif
				// #ifdef MP-BAIDU
				method = 'mini';
				// #endif
				// #ifdef MP-WEIXIN
				method = 'miniapp';
				// #endif
				// #ifdef MP-ALIPAY
				method = 'mini';
				// #endif
				// #ifdef MP-QQ
				method = 'mini';
				// #endif

				// #ifdef H5
				if (this.$jssdk.isWechat()) {
					this.payList.push({
						name: '公众号支付',
						describe: '推荐使用公众号支付',
						type: 'wechat',
						method: 'mp',
						state: true,
						select: this.isbalance ? false : true
					});
				} else {
					this.payList.push({
						name: '支付宝',
						describe: '',
						type: 'alipay',
						method: method,
						state: true,
						select: false
					}, {
						name: '微信支付',
						describe: '推荐使用微信支付',
						type: 'wechat',
						method: method,
						state: true,
						select: this.isbalance ? false : true
					});
				}
				// #endif
				// #ifndef H5
				uni.getProvider({
					service: "payment",
					success: (e) => {
						e.provider.map((value) => {
							if (value == 'alipay') {
								this.payList.push({
									name: '支付宝',
									describe: '',
									type: value,
									method: method,
									state: true,
									select: false
								});
							} else if (value == 'wxpay') {
								this.payList.push({
									name: '微信支付',
									describe: '推荐使用微信支付',
									type: 'wechat',
									method: method,
									state: true,
									select: this.isbalance ? false : true
								});
							} else if (value == 'baidu') {
								this.payList.push({
									name: '百度收银台',
									describe: '',
									type: value,
									method: method,
									state: true,
									select: false
								});
							} else if (value == 'appleiap') {
								this.payList.push({
									name: 'Apple支付',
									describe: '',
									type: 'apple',
									method: method,
									state: true,
									select: false
								});
							}
						})
					}
				});
				// #endif
			},
			//确认支付
			confirm() {
				let data = null;
				if (this.disabled) {
					return;
				}
				this.payList.map((value, index, array) => {
					if (value.select) {
						data = value;
					} else {
						return;
					}
				});
				// 判断支付是否存在
				if (!data) {
					uni.showModal({
						content: "请选择支付方式",
						showCancel: false
					});
					return;
				} else {
					this.disabled = true;
					// 获取小程序code
					// #ifdef MP
					uni.login({
						success: (e) => {
							console.log(this.pay_type, '支付类型');
							if (!this.pay_type) {
								console.log(data, e.code, '微信原支付');
								this.wanlPay(data, e.code);
							} else {
								console.log(data, e.code, '微信原支付');
								// this.caiLaiJu(data, e.code)
								this.wanlPay(data, e.code);
							}
						},
						fail: (e) => {
							uni.showModal({
								content: "无法获取微信code,原因为: " + e.errMsg,
								showCancel: false
							})
						}
					})
					// #endif
					// #ifndef MP
					// 如果是公众号获取code
					this.wanlPay(data);
					// #endif
				}
			},
			async wanlPay(data, code = null) {
				await uni.request({
					url: '/wanlshop/pay/payment',
					// url: '/wanlshop/pay/fuHavePay',
					method: 'POST',
					data: {
						order_type: this.order_type,
						type: data.type,
						method: data.method,
						code: code,
						appid: this.$wanlshop.config('miniappid'),
						order_id: this.order_id,
						token: this.token
					},
					success: res => {
						// 余额支付/小程序支付
						switch (data.type) {
							case 'balance':
								this.$store.commit('user/setUserInfo', {
									money: this.$wanlshop.bcsub(this.$store.state.user.money, this
										.price)
								});
								console.log('支付成功')
								this.paySuccess();
								break;
							case 'wechat':
								// 微信 H5支付
								if (data.method == 'wap') {
									setTimeout(() => {
										uni.showModal({
											content: '请确认微信支付是否已完成',
											confirmText: '已完成',
											cancelText: '重新支付',
											success: response => {
												if (response.confirm) {
													this.paySuccess();
												} else if (response.cancel) {
													this.confirm();
												}
											}
										});
									}, 2000);
									// 异步查询是否支付成功
									window.location.href = res.data;
									// 微信 APP支付
								} else if (data.method == 'app') {
									uni.requestPayment({
										provider: 'wxpay',
										orderInfo: res.data,
										success: (e) => {
											this.paySuccess();
										},
										fail: (e) => {
											uni.showModal({
												content: "支付失败,原因为: " + e.errMsg,
												showCancel: false
											})
										},
										complete: () => {
											this.disabled = false;
										}
									})
									// 微信 小程序支付
								} else if (data.method == 'miniapp') {
									uni.requestPayment({
										appId: res.data.appId,
										nonceStr: res.data.nonceStr,
										package: res.data.package,
										paySign: res.data.paySign,
										signType: res.data.signType,
										timeStamp: res.data.timeStamp,
										success: (e) => {
											this.paySuccess();
										},
										fail: (e) => {
											uni.showModal({
												content: "支付失败,原因为: " + e.errMsg,
												showCancel: false
											})
										}
									})
									// 微信 公众平台支付
								} else if (data.method == 'mp') {
									this.$jssdk.wxpay({
										data: res.data,
										success: e => {
											this.paySuccess();
										},
										fail: err => {
											if (err.errMsg == "chooseWXPay:ok") {
												this.$wanlshop.msg('支付成功');
											} else if (err.errMsg == "chooseWXPay:cancel") {
												this.$wanlshop.msg('支付失败，取消支付');
											} else if (err.errMsg == "chooseWXPay:fail") {
												this.$wanlshop.msg('支付失败');
											}
										}
									})
								}
								break;
							case 'alipay':
								if (data.method == 'wap') {
									this.disabled = false;
									if (this.order_type === 'goods') {
										this.$store.commit('statistics/order', {
											pay: this.$wanlshop.bcsub(this.$store.state.statistics
												.order.pay, this.payNum),
											delive: this.$wanlshop.bcadd(this.$store.state
												.statistics.order.delive, this.payNum)
										});
									}
									document.write(res.data);
								} else if (data.method == 'app') {
									uni.requestPayment({
										provider: 'alipay',
										orderInfo: res.data,
										success: (e) => {
											this.paySuccess();
										},
										fail: (e) => {
											uni.showModal({
												content: "支付失败,原因为: " + e.errMsg,
												showCancel: false
											})
										},
										complete: () => {
											this.disabled = false;
										}
									})
								}
								break;
						}
					}
				});
			},
			onSelect(key) {
				this.payList.map((value, index, array) => {
					if (index == key) {
						value.select = !value.select;
					} else {
						value.select = false;
					}
				});
			},
			// 支付成功
			paySuccess() {
				this.disabled = false;
				if (this.order_type === 'goods') {
          this.transformation()
					this.$store.commit('statistics/order', {
						pay: this.$wanlshop.bcsub(this.$store.state.statistics.order.pay, this.payNum),
						delive: this.$wanlshop.bcadd(this.$store.state.statistics.order.delive, this.payNum)
					});
				}
				this.$wanlshop.to(`/pages/page/success?type=pay&order_type=${this.order_type ? this.order_type:'goods'}`);
			},
			//财来聚支付
			onJump(payData) {
				console.log(uni.getEnterOptionsSync,'环境');
				let payDataurl = payData;
				uni.openEmbeddedMiniProgram({
					appId: 'wx939cb0b3588685ca',
					path: 'pages/hub/lite?q=' + encodeURIComponent(payDataurl),
					success: res => {
						// 打开成功
						console.log("打开成功", res);
					},
					fail: err => {
						console.log(err);
					}
				})
			},
			//财来聚支付
			async caiLaiJu(data, code = null) {
				console.log('财来聚支付');
				var self = this
				await uni.request({
					url: '/wanlshop/pay/caiLaiJu',
					method: 'POST',
					data: {
						code: code,
						appid: this.$wanlshop.config('miniappid'),
						order_id: this.order_id,
						token: this.token
					},
					success: res => {
						console.log(res, '请求调起财来聚支付');
						this.payDataList = res.data.data;
						// let payDateurl = payData.
						console.log(this.payDataList, '支付参数');
						let payData = this.payDataList.payData;
						this.onJump(payData);
						// console.log(payData.appId);
						// uni.requestPayment({
						// 	appId: payData.appId,
						// 	nonceStr: payData.nonceStr,
						// 	package: payData.package,
						// 	paySign: payData.paySign,
						// 	signType: payData.signType,
						// 	timeStamp: payData.timeStamp,
						// 	success: (e) => {
						// 		// let payData = 
						// 		this.paySuccess();
						// 	},
						// 	fail: (e) => {
						// 		uni.showModal({
						// 			content: "支付失败,原因为: " + e.errMsg,
						// 			showCancel: false
						// 		})
						// 	}
						// })
					},
					fail: res => {
						console.log(res, '请求调起财来聚支付');
					}
				});
			},
			async huolian(data, code = null) {
				console.log('火脸支付');
				var self = this
				await uni.request({
					url: '/wanlshop/pay/huoFace',
					method: 'POST',
					data: {
						code: code,
						appid: this.$wanlshop.config('miniappid'),
						order_id: this.order_id,
						token: this.token
					},
					success: res => {
						console.log(res, '请求调起火脸支付');
						var that = self
						// return false;
						const myPluginInterface = requirePlugin('huolian');
						const order_no = res.data.data.businessOrderNo
						const payParams = {
							paymentArgs: {
								orderNo: res.data.data.orderNo, // 调用api.hl.order.pay.applet接口获取的订单号
								merchantNo: res.data.data
									.merchantNo, // 调用api.hl.order.pay.applet接口获取的商户号
							},
							currentType: 'CNY' //可固定写死为CNY
						}
						let successCallBack = function(res) {
							console.log('成功回调', res)
							that.disabled = false;
							if (that.order_type === 'goods') {
								that.$store.commit('statistics/order', {
									pay: that.$wanlshop.bcsub(that.$store.state.statistics
										.order.pay, that.payNum),
									delive: that.$wanlshop.bcadd(that.$store.state.statistics
										.order.delive, that.payNum)
								});
							}

							that.$wanlshop.to(
								`/pages/page/success?type=pay&order_type=${that.order_type ? that.order_type:'goods'}&order_no=${order_no}`
							);
						}
						let errorCallBack = function(error) {
							console.log('失败回调', error)
							uni.showModal({
								content: "支付失败,原因为: " + error.errMsg,
								showCancel: false
							})
						}
						myPluginInterface.clickHuoLianPay(payParams, successCallBack, errorCallBack);
					},
					fail: res => {
						console.log(res, '请求调起火脸支付失败');
					}
				});
			},
      transformation() {
        var self = this
        var clickID = ''
        if (uni.getStorageSync('clickid')) {
          // 巨量
          clickID = uni.getStorageSync('clickid')
        }
        if (uni.getStorageSync('bxmid')) {
          // 变现猫
          clickID = uni.getStorageSync('bxmid')
        }
        if (uni.getStorageSync('qz_gdt')) {
          // 腾讯
          clickID = uni.getStorageSync('qz_gdt')
        }
        if (uni.getStorageSync('cili')) {
          // 磁力
          clickID = uni.getStorageSync('cili')
        }
        uni.request({
          url: '/wanlshop/common/zhuanhua',
          method: 'POST',
          data: {
            clickid: clickID,
            event_type: uni.getStorageSync('event_type'),
            type: true
          },
          success: res => {
            console.log("++++++++++++++++++++++++++++++++")
            console.log(res.data)
            if (res.data) {
              // 商品支付成功后调用
              if (uni.getStorageSync('clickid')) {
                self.sendtoTaq();
              }
              if (uni.getStorageSync('bxmid')) {
                self.sendtoTaqbxm();
              }
              if (uni.getStorageSync('qz_gdt')) {
                self.sendtoQzGdt()
              }
              if (uni.getStorageSync('cili')) {
                self.sendtoCiLi()
              }
            } else {
              uni.removeStorageSync('bxmid')
              uni.removeStorageSync('clickid')
              uni.removeStorageSync('qz_gdt')
              uni.removeStorageSync('cili')
              uni.removeStorageSync('host')
              uni.removeStorageSync('event_type')
            }
          }
        });
      },
      sendtoTaq:function (clickid) {
        console.log(clickid);
        console.log(clickid,'进来了？')
        var self = this;
        uni.request({
          method:'POST',
          url: 'https://analytics.oceanengine.com/api/v2/conversion',
          header: {},
          data: {
            "event_type": uni.getStorageSync('event_type'),
            "context": {
              "ad": {
                "callback": uni.getStorageSync('clickid'),//callback 这里需要填写的就是从启动参数里获取的 clickid
              }
            },
            "timestamp": new Date().getTime()
          },
          success: function(res) {
            console.log('++++++++++ success   ++++++++++++++++')
            console.log(JSON.stringify(res.data))
            uni.removeStorageSync('clickid')
            uni.removeStorageSync('event_type')
          },
          error: function(err) {
            console.log('++++++++++ error   ++++++++++++++++')
            console.log(JSON.stringify(err))
          },
          finally: function(res) {
            console.log('++++++++++ finally   ++++++++++++++++')
          }
        })
      },
      sendtoQzGdt:function () {
        var self = this;
        uni.request({
          method:'GET',
          url: 'https://tracking.e.qq.com/conv/web',
          header: {},
          data: {
            "clickid": uni.getStorageSync('qz_gdt'),
            "action_time": Math.floor(new Date().getTime() / 1000),
            "action_type": uni.getStorageSync('event_type'),
            "link": encodeURI(uni.getStorageSync('host')),
          },
          success: function(res) {
            console.log('++++++++++ success   ++++++++++++++++')
            console.log(JSON.stringify(res.data))
            uni.removeStorageSync('qz_gdt')
            uni.removeStorageSync('host')
            uni.removeStorageSync('event_type')
          },
          error: function(err) {
            console.log('++++++++++ error   ++++++++++++++++')
            console.log(JSON.stringify(err))
          },
          finally: function(res) {
            console.log('++++++++++ finally   ++++++++++++++++')
          }
        })
      },
      sendtoCiLi:function () {
        var self = this;
        uni.request({
          method:'GET',
          url: 'https://ad.partner.gifshow.com/track/activate',
          header: {},
          data: {
            "callback": uni.getStorageSync('cili'),
            "event_time": new Date().getTime(),
            "event_type": uni.getStorageSync('event_type'),
            "purchase_amount": uni.getStorageSync('purchase_amount'),
          },
          success: function(res) {
            console.log('++++++++++ success   ++++++++++++++++')
            console.log(JSON.stringify(res.data))
            uni.removeStorageSync('cili')
            uni.removeStorageSync('event_type')
            uni.removeStorageSync('purchase_amount')
          },
          error: function(err) {
            console.log('++++++++++ error   ++++++++++++++++')
            console.log(JSON.stringify(err))
          },
          finally: function(res) {
            console.log('++++++++++ finally   ++++++++++++++++')
          }
        })
      },
      sendtoTaqbxm:function () {
        uni.request({
          method:'GET',
          url: 'https://openlog.bianxianmao.com/inads/s.gif',
          header: {},
          data: {
            mt:8,
            bxmid:uni.getStorageSync('bxmid'),
            conversion_type:uni.getStorageSync('event_type'),
          },
          success: function(res) {
            console.log('++++++++++ success   ++++++++++++++++')
            console.log(JSON.stringify(res.data))
            uni.removeStorageSync('bxmid')
            uni.removeStorageSync('event_type')
          },
          error: function(err) {
            console.log('++++++++++ error   ++++++++++++++++')
            console.log(JSON.stringify(err))
          },
          finally: function(res) {
            console.log('++++++++++ finally   ++++++++++++++++')
          }
        })
      },
		}
	}
</script>

<style>
	page {
		background-color: white;
	}

	radio-group {
		display: block;
	}
	.enlargement{
		color: #FF5400;
		font-size: 16px;
		font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 30rpx 0rpx;
	}
	.fiximage{
		width: 40rpx;
		height: 130rpx;
	}
</style>